# coding: utf-8
import json
from copy import deepcopy

from fralog.FraLog import getFileLog
from werkzeug.contrib.fixers import LighttpdCGIRootFix
from flask import Flask, request, Response, redirect, jsonify
from werkzeug.datastructures import Headers
from functools import wraps
from flask import make_response
import pymongo

import MongoOper
# from module_questions.LoginFunc import check_token
import RedisOper
from result import g_ret
from globalsettings import CUR_MODE
import random


if CUR_MODE == 'dev':
    from globalsettings_dev import *
else:
    from globalsettings_prod import *

log = getFileLog()

REDIS = RedisOper.RedisOper
# 短信验证码15分钟有效
SMS_TIMEOUT = 900
APP_KEY_LIST = ['Pincn_4581214ef64d4c13dee0af7bea2d5a2f']


# 生成默认4位长度随机字符串
def create_4random_pwd(codelen=4):
    seed = "a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9".split(' ')
    random.shuffle(seed)
    print(seed)
    return ''.join(seed[0:codelen])


def allow_cross_domain(fun):
    @wraps(fun)
    def wrapper_fun(*args, **kwargs):
        '''
        跨域请求注解
        :param args:
        :param kwargs:
        :return:
        '''
        rst = make_response(fun(*args, **kwargs))
        rst.headers['Access-Control-Allow-Origin'] = '*'
        rst.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE'
        allow_headers = "Referer,Accept,Origin,User-Agent"
        rst.headers['Access-Control-Allow-Headers'] = allow_headers
        return rst

    return wrapper_fun


class Wrapmongo:
    def __init__(self, db):
        self.db = db


class MyResponse(Response):
    def __init__(self, response=None, **kwargs):
        kwargs['headers'] = ''
        headers = kwargs.get('headers')
        # 跨域控制
        origin = ('Access-Control-Allow-Origin', '*')
        methods = ('Access-Control-Allow-Methods', 'HEAD, OPTIONS, GET, POST, DELETE, PUT')
        allow_headers = ('Access-Control-Allow-Headers', 'X-Requested-With,Referer,Accept,Origin,User-Agent,'
                                                         'Content-Type')
        if headers:
            headers.add(*origin)
            headers.add(*methods)
            headers.add(*allow_headers)
        else:
            headers = Headers([origin, methods, allow_headers])
        kwargs['headers'] = headers
        return super().__init__(response, **kwargs)


def check_token(token):
    ret = deepcopy(g_ret)
    g_login, g_user_id = RedisOper.RedisOper.get_userid_bytoken(token)
    if g_login:
        ret['code'] = 200
        return g_user_id, ret
    else:
        ret['code'] = 401
        ret['msg'] = 'token验证失败'
        return None, ret


def get_param(request):
    paramt = request.data
    if paramt is None or len(paramt) < 1:
        paramts = request.values.to_dict()
        print(paramts)
        return paramts
    else:
        paramts = json.loads(request.data.decode())
        print(paramts)
        return paramts


def verify_token(func):
    @wraps(func)
    def check_token_fun(*args, **kwargs):
        # print('verify_token')
        param = request.data
        if param is None or len(param) < 1:
            param = request.values.to_dict()
        else:
            param = json.loads(request.data.decode())
        g_user_id, backret = check_token(param.get('token'))
        if g_user_id is None:
            print('verify_token false')
            # format = json.dumps(backret)
            response = jsonify(backret)
            response.status_code = 200
            return response
            # return Response(
            #     response=format,
            #     mimetype="application/json",
            #     status=200
            # )
            # return redirect("/fail")
        else:
            # print('verify_token true')
            return func(*args, **kwargs)
        return func(*args, **kwargs)
    return check_token_fun


def verify_times(func):
    @wraps(func)
    def verify_times_fun(*args, **kwargs):
        remote_ip = request.remote_addr
        enable = RedisOper.RedisOper.checkkeytimes(remote_ip, 5, 6)
        if not enable:
            print('verify_connetion time false')
            return Response(
                response=json.dumps({}),
                mimetype="application/json",
                status=404
            )
        else:
            # print('verify_connetion time true')
            return func(*args, **kwargs)
        return func(*args, **kwargs)
    return verify_times_fun


app = Flask(__name__)
app.response_class = MyResponse
app.config.update(
    DEBUG=True
)

app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)
if MONGO_DB_PWD is None or MONGO_DB_PWD == '':
    MONGOURL = 'mongodb://' + MONGO_HOST + ':' + str(MONGO_PORT) + '/'
    client = pymongo.MongoClient(MONGOURL)
else:
    MONGOURL = 'mongodb://' + MONGO_DB_USERNAME + ':' + MONGO_DB_PWD + '@' + MONGO_HOST + ':' + str(MONGO_PORT) + '/'
    client = pymongo.MongoClient(host=MONGO_HOST, port=MONGO_PORT, username=MONGO_DB_USERNAME,
                                 password=MONGO_DB_PWD, socketKeepAlive=True)
db = client[MONGO_DB_NAME]
mongo = Wrapmongo(db=db)
#
# # redis的配置
# REDIS_IP = '127.0.0.1'
# REDIS_PORT = 6379
# #
# 监控相关
task_key = 'monitor_list'
data_collection = 'responses_collection'  # 监控指标使用的数据源
email_hour = [10, 18]  # 每天10点，16点发送邮件

desc_map = {}
cache_questionid_ruleid = {}
cache_question_polor = {}
cache_select_survey = {}


rows = MongoOper.pagequery(mongo, table='desc_collection', query={}, page=1, pagesize=0)
for row in rows['data']:
    code = row.get('code')
    if code is None:
        continue
    if desc_map.get(code) is None:
        desc_map[code] = {}
    if row['id'] == 'o':
        desc_map[code]['o'] = row
    if row['id'] == 'c':
        desc_map[code]['c'] = row
    if row['id'] == 'e':
        desc_map[code]['e'] = row
    if row['id'] == 'a':
        desc_map[code]['a'] = row
    if row['id'] == 'n':
        desc_map[code]['n'] = row
rows = MongoOper.pagequery(mongo, table='questions_collection', query={}, page=1, pagesize=0)
for row in rows.get('data'):
    if row.get('rule_id') is not None:
        cache_questionid_ruleid[row.get('question_id')] = row.get('rule_id')
    if row.get('polar_type') is not None and row.get('polar_type') == '-1':
        cache_question_polor[row.get('question_id')] = '-1'
rows = MongoOper.pagequery(mongo, table='surveys_collection', query={}, page=1, pagesize=0)
for row in rows.get('data'):
    if row.get('code') is not None:
        cache_select_survey[row.get('code')] = row
log.info('--ruleid--')
log.info(cache_questionid_ruleid)


